/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers.classes;

import classes.Breadcrumbs;
import classes.HibernateUtil;
import dao.PrivateMessageDao;
import dao.UserDao;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.PrivateMessage;
import models.User;

/**
 * This controller is for composing/replying on private messages; Also it is for
 * viewing private messages.
 *
 * @author Sander
 */
public class ComposePrivateMessageController extends HttpServlet {

    /**
     * This doGet checks wether the action is composing a private message and
     * sets up attributes for the JSP file; Otherwise it will check if it will
     * get a messages id then it will check wether the action is delete, update
     * or revert the message.
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HibernateUtil hu = new HibernateUtil();
        PrivateMessageDao dao = new PrivateMessageDao(hu.openSession());

        String action = request.getParameter("action");
        // Sets the string action 
        String str_action = action.substring(0, 1).toUpperCase() + action.substring(1);

        if (action.equals("compose")) {
            if (request.getParameter("receiver") != null) {
                long receiver_id = Long.parseLong(request.getParameter("receiver"));
                // Get the user with the id of the parameter receiver
                UserDao udao = new UserDao(hu.openSession());
                User user = udao.get(receiver_id);
                if (user != null) {
                    // Set attribute with the id from the receiver and his name
                    request.setAttribute("receiver_id", receiver_id);
                    request.setAttribute("receiver_fullname", user.getFirstname() + " " + user.getInsertion() + " " + user.getLastname());
                } else { // User doesn't exists
                    response.sendRedirect("PrivateMessage");
                    return;
                }
            } else { // Parameter receiver doesn't exists
                response.sendRedirect("PrivateMessage");
                return;
            }
        } else if (request.getParameter("message") != null) {
            PrivateMessage pm = dao.get(Long.parseLong(request.getParameter("message")));
            if (action.equals("delete")) {
                String redirect = "";
                if (pm.getFolder() == 1) {
                    redirect = "inbox";
                } else if (pm.getFolder() == 2) {
                    redirect = "outbox";
                } else {
                    redirect = "trash";
                }

                if (pm.getFolder() == 3) { // If private message is in folder trash
                    dao.delete(pm);
                } else { // If private message is in folder inbox or outbox
                    pm.setFolder(3);
                    dao.update(pm);
                }

                // Redirect to the right folder
                RequestDispatcher dispatcher = request.getRequestDispatcher("PrivateMessage?folder=" + redirect);
                dispatcher.forward(request, response);
            } else if (action.equals("revert")) {
                HttpSession req = request.getSession();
                User user = (User) req.getAttribute("user");
                if (pm.getSender().getMember_id() == user.getMember_id()) { // Determine where to revert the private message to
                    pm.setFolder(2);
                } else {
                    pm.setFolder(1);
                }
                dao.update(pm);

                // Redirect to trash (depending of the action: revert)
                RequestDispatcher dispatcher = request.getRequestDispatcher("PrivateMessage?folder=trash");
                dispatcher.forward(request, response);
            } else {
                // Put the private message on status read
                pm.setStatus(0);
                dao.update(pm);
            }
            List<PrivateMessage> private_message = dao.findAllById(Long.parseLong(request.getParameter("message")));
            request.setAttribute("private_message", private_message);

            String folder = "inbox";
            if (pm.getFolder() == 2) {
                folder = "outbox";
            } else if (pm.getFolder() == 3) {
                folder = "trash";
            }

            // Breadcrumbs
            Breadcrumbs[] breadcrumbs = {
                new Breadcrumbs("Index", "Home"),
                new Breadcrumbs("PrivateMessage?folder=" + folder, folder.substring(0, 1).toUpperCase() + folder.substring(1)),
                new Breadcrumbs("ComposePrivateMessage?action=" + action, str_action)
            };
            request.setAttribute("breadcrumbs", breadcrumbs);
        }

        request.setAttribute("action", action);
        request.setAttribute("str_action", str_action);

        if (action.equals("compose")) {
            // Breadcrumbs
            Breadcrumbs[] breadcrumbs = {
                new Breadcrumbs("Index", "Home"),
                new Breadcrumbs("PrivateMessage?folder=inbox", "Inbox"),
                new Breadcrumbs("ComposePrivateMessage?action=compose", "Compose private message")
            };
            request.setAttribute("breadcrumbs", breadcrumbs);
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/compose_private_message.jsp");
        dispatcher.forward(request, response);
    }

    /**
     * This doPost checks wether the message is a reply or a new private message
     * then it sets up the private message and saves it in the database for the
     * receiver and also for the sender.
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HibernateUtil hu = new HibernateUtil();
        PrivateMessageDao dao = new PrivateMessageDao(hu.openSession());

        long id = System.nanoTime();
        String subject = request.getParameter("subject");
        User user = (User) request.getSession().getAttribute("user");
        long receiver_id = Long.parseLong(request.getParameter("to"));
        String message = request.getParameter("message");

        // Gets the id of the receiver
        UserDao ud = new UserDao(hu.openSession());
        User receiver = (User) ud.get(receiver_id);

        // PrivateMessage(id, subject, sender, receiver, message, reply, status, folder, owner)
        // If the message is a reply other attributes will be used for put it in the database
        if (request.getParameter("reply") != null) {
            // Sender
            PrivateMessage pm = new PrivateMessage(id, subject, user, receiver, message, Long.parseLong(request.getParameter("reply")), 0, 2, user);
            dao.save(pm);
            // Receiver
            pm = new PrivateMessage(id, subject, user, receiver, message, Long.parseLong(request.getParameter("reply")), 1, 1, receiver);
            dao.save(pm);
        } else {
            // Sender
            PrivateMessage pm = new PrivateMessage(id, subject, user, receiver, message, 0, 0, 2, user);
            dao.save(pm);
            // Receiver
            pm = new PrivateMessage(id, subject, user, receiver, message, 0, 1, 1, receiver);
            dao.save(pm);
        }

        hu.close();

        response.sendRedirect("PrivateMessage");
    }
}
